package com.kongjs.application.controller;

import cn.hutool.captcha.AbstractCaptcha;

import com.kongjs.application.service.impl.CaptchaService;
import com.kongjs.common.rest.annotation.Rest;
import jakarta.annotation.Resource;
import org.springframework.http.CacheControl;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Rest
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Resource
    private CaptchaService captchaService;

    @GetMapping("/{action}/image")
    public ResponseEntity<byte[]> image(@PathVariable String action) {
        if (!StringUtils.hasText(action)) {
            return ResponseEntity.badRequest().build();
        }
        AbstractCaptcha captcha = captchaService.getCaptcha();
        ResponseCookie cookie = ResponseCookie.from("captcha_" + action, captcha.getCode()).httpOnly(true).path("/").build();
        return ResponseEntity
                .ok()
                .contentType(MediaType.IMAGE_PNG)
                .cacheControl(CacheControl.noCache())
                .header("Set-Cookie", cookie.toString())
                .body(captcha.getImageBytes());
    }

    @GetMapping("/{action}/base64")
    public ResponseEntity<String> base64(@PathVariable String action) {
        if (!StringUtils.hasText(action)) {
            return ResponseEntity.badRequest().build();
        }
        AbstractCaptcha captcha = captchaService.getCaptcha();
        ResponseCookie cookie = ResponseCookie.from("captcha_" + action, captcha.getCode()).httpOnly(true).path("/").build();
        return ResponseEntity
                .ok()
                .contentType(MediaType.TEXT_PLAIN)
                .cacheControl(CacheControl.noCache())
                .header("Set-Cookie", cookie.toString())
                .body(captcha.getImageBase64Data());
    }
}
